import type { NextApiResponse } from 'next';
import { redisManager } from '@/common/database/redis';
import R from '@/common/type/response';
import { AuthenticatedRequest, withAuth } from '@common/middleware/auth';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method !== 'GET') {
    return R.error(res, '只支持GET请求');
  }

  try {
    const diagnostics = {
      timestamp: new Date().toISOString(),
      environment: {
        REDIS_HOST: process.env.REDIS_HOST || 'localhost',
        REDIS_PORT: process.env.REDIS_PORT || '6379',
        REDIS_PASSWORD: process.env.REDIS_PASSWORD ? '***' : '未设置',
        REDIS_DB: process.env.REDIS_DB || '0',
      },
      connection: {
        status: 'checking...',
        info: null as any,
        error: null as string | null,
      },
      test: {
        ping: false,
        set: false,
        get: false,
        del: false,
      }
    };

    // 检查连接状态
    try {
      const isConnected = await redisManager.isConnected();
      diagnostics.connection.status = isConnected ? 'connected' : 'disconnected';
      
      if (isConnected) {
        diagnostics.connection.info = redisManager.getConnectionInfo();
        
        // 测试基本操作
        const client = await redisManager.getClient();
        
        // 测试 PING
        try {
          await client.ping();
          diagnostics.test.ping = true;
        } catch (error: any) {
          diagnostics.test.ping = false;
          diagnostics.connection.error = error.message;
        }
        
        // 测试 SET
        try {
          await client.set('test:diagnose', 'test_value', 'EX', 60);
          diagnostics.test.set = true;
        } catch (error: any) {
          diagnostics.test.set = false;
        }
        
        // 测试 GET
        try {
          const value = await client.get('test:diagnose');
          diagnostics.test.get = value === 'test_value';
        } catch (error: any) {
          diagnostics.test.get = false;
        }
        
        // 测试 DEL
        try {
          await client.del('test:diagnose');
          diagnostics.test.del = true;
        } catch (error: any) {
          diagnostics.test.del = false;
        }
      }
    } catch (error: any) {
      diagnostics.connection.status = 'error';
      diagnostics.connection.error = error.message;
    }

    R.success(res, diagnostics);
  } catch (error: any) {
    console.error('Redis 诊断错误:', error);
    R.error(res, error.message || 'Redis 诊断失败');
  }
}

export default withAuth(handler); 